//
//  PPTemplateViewController.m
//  pickpic
//
//  Created by 胡文广 on 2017/3/25.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPTemplateViewController.h"
#import "PPTemplateTableViewCell.h"
#import "PPTemplateModel.h"
#import "PPPhotoBrowserController.h"
#import "UAProgressView.h"
#import "PPTemplateCoverFrame.h"
//#import <JCDownloader/JCDownloader.h>
#import "PPHomeAlbumModel.h"
#import "PPTemplateDescModel.h"
#import "PPTemplateInnerModel.h"
#import "PPTemplateShareModel.h"
#import "PPEbookAlbum.h"

@interface PPTemplateViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *templateList;
@property (nonatomic,assign) NSInteger currentPage;
@property (nonatomic,strong) JCDownloadOperation *operation;
@property (nonatomic,strong) JCDownloadQueue *operationQueue;

@property (nonatomic,strong) NSMutableArray *downloads;
@property (nonatomic,assign) BOOL isEmploy;

@property (nonatomic,strong) NSMutableArray *tempDownLoadURLs;


@property (nonatomic,strong) NSMutableArray<JCDownloadOperation *> *queues;

@property (nonatomic,assign) NSInteger currentTag;
@end

@implementation PPTemplateViewController
NSString *const JCTImageDownloadGroupId = @"kJCTImageDownloadGroupId";

static NSString *const templateCellID = @"TemplateTableViewCell";
static NSString * const kURLKey = @"URL";
static NSString * const kNameKey = @"name";
- (NSMutableArray<JCDownloadOperation *> *)queues{

    if (!_queues) {
        _queues = [NSMutableArray array];
    }
    return _queues;
}
- (NSMutableArray *)tempDownLoadURLs{

    if (!_tempDownLoadURLs) {
        _tempDownLoadURLs = [NSMutableArray array];
    }
    return _tempDownLoadURLs;
}
- (NSMutableArray *)downloads{

    if (!_downloads) {
        
        _downloads = [NSMutableArray array];
    }
    return _downloads;
}
- (NSMutableArray *)templateList{
    if (!_templateList) {
        _templateList = [NSMutableArray array];
    }
    return _templateList;
}
- (JCDownloadQueue *)operationQueue{

    if (!_operationQueue) {
        _operationQueue = [JCDownloadQueue sharedQueue];
    }
    return _operationQueue;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    //注册fonts目录下面的所有字体文件
    
//    [[PPUserAccount currentUser] registerFont];
    

}
- (void)loadView{
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    self.view = _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"电子书模版列表";
    self.view.backgroundColor = WHITE;
    
    
    if (IS_IOS_8) {
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: PFFontBold(17),NSForegroundColorAttributeName:BLACK}];
    }else{
        
        
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: PPFONT(PFBold, 17),NSForegroundColorAttributeName:BLACK}];
    }
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全部下载" style:UIBarButtonItemStylePlain target:self action:@selector(downLoadAll:)];
    
    if (IS_IOS_8) {
          [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16)} forState:UIControlStateNormal];
    }else{
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPTemplateTableViewCell class]) bundle:nil] forCellReuseIdentifier:templateCellID];
    
    self.tableView.mj_header = [YKRefreshHeaderDIY headerWithRefreshingTarget:self refreshingAction:@selector(loadTemplateList:)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [YKRefreshFooterDIY footerWithRefreshingTarget:self refreshingAction:@selector(loadTemplateList:)];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadActon:) name:JCTTTFDownloadGroupId object:nil];
    
    
    NSArray *fontFamilys = [UIFont familyNames];
    for (NSString *familyName in fontFamilys) {
        NSLog(@"family name : %@",familyName);
        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
        for (NSString *fontName in fontNames) {
            NSLog(@"font name : %@",fontName);
        }
    }
    
    
    
 
}

- (void)loadTemplateList:(YKRefreshHeaderDIY *)refresh{
    
    BOOL isHead = [refresh isKindOfClass:[YKRefreshHeaderDIY class]];
    if (isHead) {
        self.currentPage = 1;
    }else{
        self.currentPage ++;
    }
    
    NSDictionary *info = @{
                           @"page":@(self.currentPage),
                           @"rows":@(10),
                           };
    
    NSString *deviceType;
    
    PPLog(@"--- %f",[UIScreen mainScreen].bounds.size.height);
    
    if ([UIScreen mainScreen].bounds.size.height <= 568) {
        deviceType = @"5s";
    }else if ([UIScreen mainScreen].bounds.size.height <= 667){
        deviceType = @"6"; //667
    }else {
        deviceType = @"6p"; //736
    }
    NSDictionary *dict = @{
                           @"pageInfo":info,
                           @"deviceType":deviceType,
                           };
    [PPNetworkService getEbookListWithparams:dict callback:^(id data, NSError *error) {
        PPLog(@"模板列表 = %@",data);
        if (isHead) {
            self.templateList = [NSMutableArray array];
        }
        NSArray *templates = data[@"rows"];
    
        NSInteger total = [data[@"total"]  integerValue];
        for (id dict in templates) {
            

            
            PPTemplateModel *templateM = [PPTemplateModel yy_modelWithDictionary:[dict[@"templateData"] cd_objectFromJSONString]];
            templateM.series = dict[@"series"];
            templateM.eBookTemplateId = dict[@"eBookTemplateId"];
            templateM.orderNum = [dict[@"orderNum"] integerValue];
            
            if (templateM.orderNum > 0) {
                if (templateM.orderNum == 1) {
                    templateM.orderNum = 6;
                }else if (templateM.orderNum == 2){
                    templateM.orderNum = 7;
                }else{
                    templateM.orderNum = templateM.orderNum - 2;
                }
            }
            
            if (templateM.orderNum == 0) {
                templateM.downloadType = PPTemplateDownLoadTypeEmploy;
            }else{
                templateM.downloadType = PPTemplateDownLoadTypeNot;
            }
            
//            NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
            NSMutableArray *templateArr = [NSKeyedUnarchiver unarchiveObjectWithFile:kTemplatePlist];
            
            if (templateArr.count > 0 && templateM.orderNum != 0) {
                for (id tempDict in templateArr) {
                    
                    PPTemplateModel *temp;
                    if ([tempDict isKindOfClass:[PPTemplateModel class]]) {
                        temp = (PPTemplateModel *)tempDict;
                    }else{
                        temp = [PPTemplateModel yy_modelWithDictionary:dict];
                    }
//                    PPTemplateModel *temp = [PPTemplateModel yy_modelWithDictionary:dict];
                    if ([temp.eBookTemplateId isEqualToString:templateM.eBookTemplateId]) {
                         templateM.downloadType = temp.downloadType;
                        for (id ebookAlbumDict  in temp.albums) {
                            PPEbookAlbum *ebookA;
//                            = [PPEbookAlbum yy_modelWithDictionary:ebookAlbum];
                            if ([ebookAlbumDict isKindOfClass:[PPEbookAlbum class]]) {
                                ebookA = (PPEbookAlbum *)ebookAlbumDict;
                            }else{
                                ebookA = [PPEbookAlbum yy_modelWithDictionary:ebookAlbumDict];
                            }
                            if (ebookA.albumID == self.albumM.albumID) {
                                templateM.downloadType = ebookA.downloadType;
                                self.isEmploy = YES;
                            }
                        }
                    }
                }
            }
            
            
            PPTemplateCoverFrame *coverF = [PPTemplateCoverFrame yy_modelWithDictionary:[dict[@"templateData"] cd_objectFromJSONString]];
            coverF.series = dict[@"series"];
            coverF.orderNum = [dict[@"orderNum"] integerValue];
           
            if (coverF.orderNum > 0) {
                if (coverF.orderNum == 1) {
                    coverF.orderNum = 6;
                }else if (coverF.orderNum == 2){
                    coverF.orderNum = 7;
                }else{
                    coverF.orderNum = coverF.orderNum - 2;
                }
            }

            coverF.url11 = templateM.url11;
            templateM.coverFrameM = coverF;
            
            PPTemplateDescModel *descM = [PPTemplateDescModel yy_modelWithDictionary:[dict[@"templateData"] cd_objectFromJSONString]];
            descM.series = dict[@"series"];
            descM.orderNum = [dict[@"orderNum"] integerValue];
            if (descM.orderNum == 1) {
                descM.orderNum = 6;
            }else if (descM.orderNum == 2){
                descM.orderNum = 7;
            }else{
                descM.orderNum = descM.orderNum - 2;
            }

            
            descM.url11 = templateM.url11;
            templateM.descModel = descM;
            
            PPTemplateInnerModel *innerModel = [PPTemplateInnerModel yy_modelWithDictionary:[dict[@"templateData"] cd_objectFromJSONString]];
            innerModel.series = dict[@"series"];
            innerModel.orderNum = [dict[@"orderNum"] integerValue];
            
            if (innerModel.orderNum > 0) {
                
                if (innerModel.orderNum == 1) {
                    innerModel.orderNum = 6;
                }else if (innerModel.orderNum == 2){
                    innerModel.orderNum = 7;
                }else{
                    innerModel.orderNum = innerModel.orderNum - 2;
                }
            }
            
            innerModel.url11 = templateM.url11;
            templateM.innerModel = innerModel;
            
            PPTemplateShareModel *shareModel = [PPTemplateShareModel yy_modelWithDictionary:[dict[@"templateData"] cd_objectFromJSONString]];
            shareModel.series = dict[@"series"];
            shareModel.orderNum = [dict[@"orderNum"] integerValue];
            
            if (shareModel.orderNum > 0) {
                if (shareModel.orderNum == 1) {
                    shareModel.orderNum = 6;
                }else if (shareModel.orderNum == 2){
                    shareModel.orderNum = 7;
                }else{
                    shareModel.orderNum = shareModel.orderNum - 2;
                }
            }
            
            shareModel.url11 = templateM.url11;
            templateM.shareModel = shareModel;
            templateM.musicUrl = shareModel.musicUrl;
            if (!templateM.previewUrls) {
                templateM.previewUrls = [NSMutableArray array];
            }
            if (templateM.url2) {
                [templateM.previewUrls addObject:templateM.url2];
            }
            if (templateM.url3) {
                [templateM.previewUrls addObject:templateM.url3];
            }
            if (templateM.url4) {
                [templateM.previewUrls addObject:templateM.url4];
            }
            if (templateM.url5) {
                [templateM.previewUrls addObject:templateM.url5];
            }
            if (templateM.url6) {
                [templateM.previewUrls addObject:templateM.url6];
            }

            if (templateM) {
                [self.templateList addObject:templateM];
                
                if (self.isEmploy) {
                    PPTemplateModel *template = [self.templateList firstObject];
                    template.downloadType = PPTemplateDownLoadTypeFinish;
                    [self.templateList replaceObjectAtIndex:0 withObject:template];
                }
            }
           
            PPLog(@"URL8 {%@ = %@ = %@ = %@}",templateM.coverFrameM.titleName,templateM.title,templateM.coverFrameM.titlePostScript,templateM.url8);
        }
    
        [self.tableView reloadData];
        [refresh endRefreshing];
        self.tableView.mj_footer.hidden = self.templateList.count >= total;
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.templateList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    PPTemplateTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:templateCellID];
//    cell.downLoadBtn.tag = indexPath.row;
//    [cell.downLoadBtn addTarget: self action:@selector(downLoadTemplate:) forControlEvents:UIControlEventTouchUpInside];
    cell.PogressBg.tag = indexPath.row;
    cell.PogressBg.userInteractionEnabled = YES;
    cell.progressV.tag = indexPath.row;
    cell.templateM = self.templateList[indexPath.row];
    cell.progressV.didSelectBlock = ^(UAProgressView *progressView){
        
        if (!progressView) {
            PPLog(@"未发现点击事件");
            return ;
        }

        //开始
        [self downLoadTemplateProgressTag:progressView.tag isAll:NO];
        
    };
    
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = COLORA(249, 249, 249);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickProgressBg:)];
    [cell.PogressBg addGestureRecognizer:tap];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return PPTemplateTableViewCell_H;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PPTemplateModel *templateM = self.templateList[indexPath.row];
    
//    if (templateM.downloadType == PPTemplateDownLoadTypeEmploy) {
//        //已下载样式
//        /// 获取相册 - 图片- 相册描述 - 相册
//        PPPhotoBrowserController *browserVc = [[PPPhotoBrowserController alloc] init];
//        browserVc.type = PPPhotoBrowserTypeEbook;
//        //封面data模型+frame模型
//        self.albumCoverModel.url = templateM.url7;
//        self.albumCoverModel.photoFrameImage = templateM.coverImg;
//        templateM.coverFrameM.coverModel = self.albumCoverModel;
//        
//        browserVc.templateM = templateM;
//        browserVc.albumModel = self.albumM;
//        browserVc.albumCoverModel = templateM.coverFrameM.coverModel;
//        [self.navigationController pushViewController:browserVc animated:YES];
//        
//    }else{
        //未下载样式
//        PPTemplateModel *templateM = self.templateList[indexPath.row];
        PPLog(@"%@",templateM.previewUrls);
        PPPhotoBrowserController *browserVc = [[PPPhotoBrowserController alloc] init];
        browserVc.BlockDownLoadTemplate = ^{
//            PPTemplateTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
            [self downLoadTemplateProgressTag:indexPath.row isAll:YES];
            
        };
        
        browserVc.BlockEmployTemplate = ^(PPTemplateModel *templateModel){
            [self.navigationController popViewControllerAnimated:NO];
            
            if ([self.delegate respondsToSelector:@selector(templateViewController:employEbooktemplateModel:)]) {
                [self.delegate templateViewController:self employEbooktemplateModel:templateModel];
            }
            
        };
        
        browserVc.type = PPPhotoBrowserTypeTemplate;
        browserVc.templateM = templateM;
        [self.navigationController pushViewController:browserVc animated:YES];
//    }
    
    

    
    
}
///MARK:全部下载
- (void)downLoadAll:(id)sender{

//    NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
    NSMutableArray *templateArr = [NSKeyedUnarchiver unarchiveObjectWithFile:kTemplatePlist];
    
    if (!templateArr) {
        templateArr = [NSMutableArray array];
    }
    for (int i = 0; i<self.templateList.count; i++) {
        NSIndexPath *indexP = [NSIndexPath indexPathForRow:i inSection:0];
        PPTemplateModel *templateM = self.templateList[indexP.row];
        
        if (templateM.downloadType != PPTemplateDownLoadTypeFinish && templateM.downloadType != PPTemplateDownLoadTypeEmploy) {
                [self downLoadTemplateProgressTag:indexP.row  isAll:YES];
            
        }
        
    }
    
}


- (void)clickProgressBg:(UITapGestureRecognizer *)tapBgRec{
    
    UIImageView *bg = (UIImageView *)tapBgRec.view;
    [self downLoadTemplateProgressTag:bg.tag isAll:NO];
}

//"url7":"",//封面底图地址 — 电子书封面背景图地址
//"url8":"",//封面标题字体包
//"url9":"",//封面用户名字体包
//"url10":"",//相册描述与内文描述字体包
//"url11":"",//封底底图地址 —- 电子书封底地址
///MARK:单个下载
- (void)downLoadTemplateProgressTag:(NSInteger)progressTag isAll:(BOOL)isAll{

    PPTemplateModel *templateM = self.templateList[progressTag];
    
    self.currentTag = progressTag;
    
//    NSIndexPath *indexP = [NSIndexPath indexPathForRow:progressTag inSection:0];
    
//    PPTemplateTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexP];
    
    if (templateM.downloadType == PPTemplateDownLoadTypeFinish || templateM.downloadType == PPTemplateDownLoadTypeEmploy) {
        
        if (templateM.downloadType == PPTemplateDownLoadTypeFinish) {
            [self.navigationController popViewControllerAnimated:NO];
             [self downShareImgurl:templateM.coverFrameM.coverModel.url];
            if ([self.delegate respondsToSelector:@selector(templateViewController:employEbooktemplateModel:)]) {
                [self.delegate templateViewController:self employEbooktemplateModel:templateM];
            }
        }else{
            if (!isAll) {
                [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:progressTag inSection:0]];
            }
        }
        return;
    
    }
    
    NSMutableArray *downloadList = [self addDownloadlistWith:templateM];
    if (downloadList.count <= 0) { return; }
    //----- 加载

    dispatch_group_t group =dispatch_group_create();
    
    for (int i = 0; i<downloadList.count; i++) {
        dispatch_group_enter(group);
        NSDictionary *downDict = self.downloads[i];
        JCDownloadItem * downloadItem = [[JCDownloadItem alloc ] init ];
        downloadItem.downloadUrl = downDict[kURLKey] ;
        downloadItem.downloadFilePath = kTemplatePath(downDict[kNameKey]);
        JCDownloadOperation *operation = [JCDownloadOperation operationWithItem:downloadItem];
        
        [operation startWithProgressBlock:^(NSProgress *progress) {
            
            PPTemplateTableViewCell *templateCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:progressTag inSection:0]];
            if (templateM.url7 == downloadItem.downloadUrl) {
                templateM.downloadType = PPTemplateDownLoadTypeBeing;
                [(UIImageView *)templateCell.progressV.centralView setBackgroundColor:BLACK];
                [templateCell.progressV setProgress:progress.fractionCompleted animated:YES];
                templateM.receivedLength = progress.fractionCompleted;
            }
            
            
//                if (downloadList.count == 3 && templateM.url8 == downloadItem.downloadUrl) {
//                    
//                    templateM.downloadType = PPTemplateDownLoadTypeBeing;
//                    [templateCell.progressV setProgress:progress.fractionCompleted animated:YES];
//
//                    templateM.receivedLength = progress.fractionCompleted;
//                }else if (downloadList.count == 2 && templateM.url7 == downloadItem.downloadUrl){
//                    templateM.downloadType = PPTemplateDownLoadTypeBeing;
//                    [templateCell.progressV setProgress:progress.fractionCompleted animated:YES];
//                    templateM.receivedLength = progress.fractionCompleted;
//                }
//
//            
//            
//            [self.templateList replaceObjectAtIndex:progressTag withObject:templateM];
//            
//            if (!cell) {
//                if (templateM.receivedLength < progress.fractionCompleted && templateM.url8 == downloadItem.downloadUrl) {
//                    templateM.receivedLength = progress.fractionCompleted;
//                }
//                [self.templateList replaceObjectAtIndex:progressTag withObject:templateM];
//                [self.tableView reloadData];
//            }
            
            
        } completionBlock:^(NSURL *filePath, NSError *error) {
            PPLog(@"下载完成--%@ - %@ -\n filePath = %@",templateM.url8,templateM.title,filePath);
            PPTemplateTableViewCell *templateCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:progressTag inSection:0]];
//            if (templateCell) {
//                if (downloadList.count == 3 && templateM.url8 == downloadItem.downloadUrl) {
//                        templateM.downloadType = PPTemplateDownLoadTypeFinish;
//                        templateM.receivedLength = 0.00;
//                         [templateCell.progressV setProgress:0 animated:YES];
//                }else if (downloadList.count == 2 && templateM.url7 == downloadItem.downloadUrl){
//                    templateM.downloadType = PPTemplateDownLoadTypeFinish;
//                      templateM.receivedLength = 0.00;
//                    [templateCell.progressV setProgress:0 animated:YES];
//                }
//            }else{
//                templateM.receivedLength = 0.00;
//            }
//
//        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:progressTag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
            
            //下载操作完成
            if (templateM.url7 == downloadItem.downloadUrl) {
                
                templateM.coverImagePath = filePath;
                UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
                templateM.coverImgString = [UIImageJPEGRepresentation(img, 0.8) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                [self.templateList replaceObjectAtIndex:progressTag withObject:templateM];
                
                templateM.downloadType = PPTemplateDownLoadTypeFinish;
                
                templateM.receivedLength = 0.00;
                [templateCell.progressV setProgress:0 animated:YES];
            }
            
//            dispatch_group_leave(group);
            
//            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:progressTag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
             dispatch_group_leave(group);
           
        }];
        
//          [self.templateList replaceObjectAtIndex:progressTag withObject:templateM];

    }
//    WEAKSELF
    
    dispatch_group_notify(group,dispatch_get_main_queue(), ^(){
        PPLog(@"SB下载完成 %@",templateM.title);
        //单个模板数据下载完成
        templateM.downloadType = PPTemplateDownLoadTypeFinish;
        
        [self.templateList replaceObjectAtIndex:progressTag withObject:templateM];

        [self.tableView reloadData];
        
        
//        NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
        NSMutableArray *templateArr = [NSKeyedUnarchiver unarchiveObjectWithFile:kTemplatePlist];
        if (!templateArr) {
            templateArr = [NSMutableArray array];
        }
//        NSData *dict = [templateM yy_modelToJSONData];
        
//        NSDictionary *dict = [[templateM yy_modelToJSONData] yy_modelToJSONObject];
//        
//
        [templateArr addObject:templateM];

//        [templateArr writeToFile:kTemplatePlist atomically:YES];
        [NSKeyedArchiver archiveRootObject:templateArr toFile:kTemplatePlist];
        
        
        PPLog(@"%@",NSHomeDirectory());
        
    });

}
- (NSDictionary*)getObjectData:(id)obj {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
    
    for(int i = 0;i < propsCount; i++) {
        
        objc_property_t prop = props[i];
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value == nil) {
            
            value = [NSNull null];
        } else {
            value = [self getObjectInternal:value];
        }
        [dic setObject:value forKey:propName];
    }
    
    return dic;
}
- (id)getObjectInternal:(id)obj {
    
    if([obj isKindOfClass:[NSString class]]
       ||
       [obj isKindOfClass:[NSNumber class]]
       ||
       [obj isKindOfClass:[NSNull class]]) {
        
        return obj;
        
    }
    if([obj isKindOfClass:[NSArray class]]) {
        
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        
        for(int i = 0; i < objarr.count; i++) {
            
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
        }
        return arr;
    }
    if([obj isKindOfClass:[NSDictionary class]]) {
        
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        
        for(NSString *key in objdic.allKeys) {
            
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }
        return dic;
    }
    return [self getObjectData:obj];
    
}

#pragma mark - 字体注册
//注册指定路径下的字体文件
//下载回来的字体文件如果不做处理是不能直接使用的，使用前需要先注册然后才能使用
- (void)registerFontPath:(NSURL *)fontPath model:(PPTemplateModel *)model{
    if (!fontPath)
    {
        return;
    }
    CFErrorRef error;
    CGDataProviderRef providerRef = CGDataProviderCreateWithURL((__bridge CFURLRef)fontPath);

    CGFontRef font = CGFontCreateWithDataProvider(providerRef);
    if (! CTFontManagerRegisterGraphicsFont(font, &error))
    {
        //注册失败
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"%@ Failed to load font: %@",model.title, errorDescription);
        CFRelease(errorDescription);
    }
    CFRelease(font);
    CFRelease(providerRef);

}



#pragma mark - 单个模板
- (NSMutableArray *)addDownloadlistWith:(PPTemplateModel *)templateM
{
    self.downloads = [NSMutableArray array];

//    if ([templateM.url8 isValid] && ![self.tempDownLoadURLs containsObject:templateM.url8]) {
//        [ self.downloads addObject:@{ kURLKey :templateM.url8,
//                                      kNameKey:[NSString stringWithFormat:@"%@_URL8.TTF",templateM.eBookTemplateId]}];
//        
//        [self.tempDownLoadURLs addObject:templateM.url8];
//    }
    
    if ([templateM.url7 isValid]&&![self.tempDownLoadURLs containsObject:templateM.url7]) {
        [ self.downloads addObject:@{ kURLKey :templateM.url7,
                                      kNameKey:[NSString stringWithFormat:@"%@_URL7",templateM.eBookTemplateId] }];
        [self.tempDownLoadURLs addObject:templateM.url7];
    }
    
//    if ([templateM.url10 isValid]&&![self.tempDownLoadURLs containsObject:templateM.url10]) {
//        [ self.downloads addObject:@{ kURLKey : templateM.url10,
//                                      kNameKey: [NSString stringWithFormat:@"%@_URL10.TTF",templateM.eBookTemplateId]}];
//        
//        [self.tempDownLoadURLs addObject:templateM.url10];
//    }

//    [UIImage cacheShareCover:templateM.shareUrl];
    [self downShareImgurl:templateM.shareUrl];
    [self downShareImgurl:templateM.url11];
    
    return _downloads;
}


- (void)downShareImgurl:(NSString *)url{

    dispatch_queue_t asynchronousQueue = dispatch_queue_create("imageDownloadQueue", NULL);
    //创建异步线程
    dispatch_async(asynchronousQueue, ^{
        [UIImage cacheShareCover:url];
    });
    
}

@end
